package com.muapet.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.muapet.model.Admin;
import com.muapet.model.Privilege;
import com.muapet.service.IAdminService;
import com.muapet.util.Md5Utils;
import com.muapet.util.constants.MyConstants;

@Controller
@RequestMapping("/admin")
public class AdminController {
	private IAdminService adminService;

	@Autowired
	public void setAdminService(IAdminService adminService) {
		this.adminService = adminService;
	}

	@RequestMapping("/home")
	public ModelAndView home() {
		ModelAndView mav = new ModelAndView("mgnt/home");
		return mav;
	}

	@RequestMapping("/tolist")
	public ModelAndView tolist() {
		ModelAndView mav = new ModelAndView("mgnt/adminList");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/listAdmin")
	@ResponseBody
	public String listAdmin() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("msg", "success");
		resultMap.put("adminList", adminService.listAdmins());
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping("/toAdd")
	public ModelAndView toAdd() {
		ModelAndView mav = new ModelAndView("mgnt/addAdmin");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/addAdmin")
	@ResponseBody
	public String addAdmin(String loginname) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (adminService.checkSameLoginname(loginname)) {
			String PwdMd5 = Md5Utils.md5(loginname + "qaz");
			Admin admin = new Admin();
			admin.setLoginname(loginname);
			admin.setPassword(PwdMd5);
			adminService.addAdmin(admin);
			resultMap.put("msg", "success");
		} else {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "登录名重复！");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/checkSameLoginname")
	@ResponseBody
	public String checkSameLoginname(String loginname) {
		Map<String, Boolean> resultMap = new HashMap<String, Boolean>();
		resultMap.put("valid", adminService.checkSameLoginname(loginname));
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/initPassword")
	@ResponseBody
	public String initPassword(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Admin admin = adminService.findById(id);
		if (admin == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "账号不存在！");
		} else if (admin.getId() == 1) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "无法对根用户操作！");
		} else {
			String PwdMd5 = Md5Utils.md5(admin.getLoginname() + "qaz");
			admin.setPassword(PwdMd5);
			adminService.updateAdmin(admin);
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(path = "/updatePassword")
	public ModelAndView updatePassword(HttpServletRequest request) {
		ModelAndView mav;
		mav = new ModelAndView("mgnt/updatePassword");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/updatePwd")
	@ResponseBody
	public String updatePwd(String password, String oldPassword,
			HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String oldPwdMd5 = Md5Utils.md5(oldPassword);
		String PwdMd5 = Md5Utils.md5(password);
		Admin loginAdmin = (Admin) request.getSession().getAttribute(
				"loginAdmin");
		if (oldPassword != null && loginAdmin.getPassword().equals(oldPwdMd5)) {
			loginAdmin.setPassword(PwdMd5);
			adminService.updateAdmin(loginAdmin);
			resultMap.put("msg", "success");
			HttpSession session = request.getSession();
			if (session != null) {
				session.invalidate();
			}
		} else {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "原密码不正确！");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/deleteAdmin")
	@ResponseBody
	public String deleteAdmin(Integer id, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Admin loginAdmin = (Admin) request.getSession().getAttribute(
				"loginAdmin");
		if (id == 1) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "根用户无法删除！");
		} else if (loginAdmin.getId().equals(id)) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "不能删除自己！");
		} else if (adminService.findById(id) == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "该管理员不存在，请刷新重试！");
		} else {
			adminService.deleteAdmin(id);
			resultMap.put("msg", "success");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping("/privilegeMgnt")
	public ModelAndView privilegeMgnt() {
		ModelAndView mav = new ModelAndView("mgnt/privilegeMgnt");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/listPrivilege")
	@ResponseBody
	public String listPrivilege() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("msg", "success");
		resultMap.put("privilegeList", adminService.listAllPrivileges());
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping("/newPrivilege")
	public ModelAndView addPrivilege() {
		ModelAndView mav = new ModelAndView("mgnt/newPrivilege");
		return mav;
	}

	@RequestMapping("/editPrivilege")
	public ModelAndView editPrivilege(Integer id) {
		ModelAndView mav;
		Privilege privilege = adminService.findPrivilegeById(id);
		if (privilege == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "找不到该权限");
		} else {
			mav = new ModelAndView("mgnt/newPrivilege");
			mav.addObject("editingPriv", privilege);
		}
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/addPrivilege")
	@ResponseBody
	public String addPrivilege(Privilege privilege) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		if (privilege.getId() != null && privilege.getId() != 0) {
			Privilege oldprivilege = adminService.findPrivilegeById(privilege
					.getId());
			if (oldprivilege.getUrl().equals(privilege.getUrl())
					|| adminService.checkURL(privilege.getUrl())) {
				adminService.updatePrivilege(privilege);
				resultMap.put("msg", "success");
			} else {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "权限路径重复！");
			}
		} else {
			if (adminService.checkURL(privilege.getUrl())) {
				adminService.addPrivilege(privilege);
				resultMap.put("msg", "success");
			} else {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "权限路径重复！");
			}
		}

		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/deletePrivilege")
	@ResponseBody
	public String deletePrivilege(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (adminService.deletePrivilege(id) > 0) {
			resultMap.put("msg", "success");
		} else {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "找不到该权限，请刷新界面！");
		}
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request, String loginname,
			String password) {
		ModelAndView mav;
		Admin admin = adminService.login(loginname, Md5Utils.md5(password));
		if (admin != null) {
			Set<String> privileges = new HashSet<String>();
			request.getSession().setAttribute("loginAdmin", admin);
			List<Privilege> privilegeList = adminService.listPrivilegesInuse();
			for (Privilege privilege : privilegeList) {
				privileges.add(MyConstants.BASE_URL + privilege.getUrl());
			}
			request.getSession().setAttribute("privileges", privileges);
			mav = new ModelAndView("mgnt/home");
		} else {
			mav = new ModelAndView("error");
			mav.addObject("msg", "登录失败");
		}
		return mav;
	}

	@RequestMapping("/logout")
	public ModelAndView logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session != null) {
			session.invalidate();
		}
		return new ModelAndView("loginForAdmin");
	}
}
